<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:7777/hello");
        //接收服务端发送过来的消息
        socket.onmessage = function (ev) {
            var resText = document.getElementById('resText');
            resText.value = resText.value + "\n" + ev.data;
        }
        //连接成功
        socket.onopen = function (ev) {
            var resText = document.getElementById('resText');
            resText.value = "连接成功...";
        }
        //连接关闭
        socket.onclose = function (ev) {
            var resText = document.getElementById('resText');
            resText.value = resText.value + "\n" + "连接断开...";
        }

        //发送消息
        function send(msg) {
            if (!socket) {
                return;
            }
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(msg);
            }else {
                alert("连接没有开启...")
            }
        }
    } else {
        alert("当前浏览器不支持webSocket")
    }
</script>

<form onsubmit="return false">
    <textarea style="width: 300px;height: 300px" name="msg"></textarea>
    <input type="button" value="发送消息" onclick="send(this.form.msg.value)">
    <textarea style="width: 300px;height: 300px" id="resText"></textarea>
    <input type="button" value="清空消息" onclick="document.getElementById('resText').value=''">
</form>
</body>
</html>